//
//  BaseRequest.m
//  TuYangTu
//
//  Created by Jpwang on 16/10/10.
//  Copyright © 2016年 Jpwang. All rights reserved.
//

#import "BaseRequest.h"

//网络不通时定义code和msg
#define kNetworkUnavailableText @"呃，网络给跪了，您确定有网络吗？"
#define kNetworkUnavailableCode -1

//定义网络请求返回关键字
//#define kResultCode         @"ResultCode"
//#define kResultMsg          @"ResultMsg"
//#define kResultData         @"Data"

#define isPrint


@implementation BaseRequest

- (instancetype)init {
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
        Reachability *reach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
        [reach startNotifier];
        _networkStatus = reach.currentReachabilityStatus;
        mIsWiFi = [reach isReachableViaWiFi];
#ifdef isPrint
        NSLog(@"----网络状态---%@", _networkStatus==1?@"非WiFi网络下":_networkStatus==2?@"WiFi网络下":@"网络不可达");
#endif
    }
    return self;
}


//网络改变通知
- (void)reachabilityChanged:(NSNotification *)note {
    Reachability* curReach = [note object];
    NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
    _networkStatus = curReach.currentReachabilityStatus;
    mIsWiFi = [curReach isReachableViaWiFi];
#ifdef isPrint
    NSLog(@"----网络状态---%@", _networkStatus==1?@"非WiFi网络下":_networkStatus==2?@"WiFi网络下":@"网络不可达");
#endif
}

//网络是否畅通
- (BOOL) isConnectionAvailable {
    return _networkStatus != NotReachable;
}

- (BOOL) isWiFi {
    return mIsWiFi;
}


//日期生成文件名
- (NSString *)filenameFromDate:(NSDate *)date {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *str = [formatter stringFromDate:date];
    return str;
}

//设置header信息
- (void)setHeader:(void (^)(AFHTTPRequestSerializer <AFURLRequestSerialization> * requestSerializer))header {
    mBlock = [header copy];
}

- (RACSignal *)postJson:(NSDictionary *)body url:(NSString *)url{
    if (mBlock) {
        mBlock(self.requestSerializer);
    }
#ifdef isPrint
    NSDictionary *header = self.requestSerializer.HTTPRequestHeaders;
    NSLog(@"----postJson----\n%@",[NSDictionary dictionaryWithObjectsAndKeys:@"POST",@"Method",url,@"RequestURL",body,@"Params",header,@"header",nil]);
#endif
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];
        NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
        NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:url parameters:nil error:nil];
        req.timeoutInterval= 10;
        [req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
        [[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
            if (!error) {
                NSLog(@"Reply JSON: %@", responseObject);
                [self handleResult:subscriber responseObject:responseObject operation:nil url:url];
            } else {
                [subscriber sendError:error];
                [subscriber sendCompleted];
                NSLog(@"----请求结束----");
                NSLog(@"%@", [NSDictionary dictionaryWithObjectsAndKeys:url, @"RequestURL",error, @"ResultData", nil]);
            }
        }] resume];
        return nil;
    }];
    
}

//POST图片
- (RACSignal *)post:(NSString *)url parms:(NSDictionary *)parms forImage:(UIImage *)image imageName:(NSString *)name {
    if (mBlock) {
        mBlock(self.requestSerializer);
    }
#ifdef isPrint
    NSDictionary *header = self.requestSerializer.HTTPRequestHeaders;
    NSLog(@"--上传图片请求开始--\n%@",[NSDictionary dictionaryWithObjectsAndKeys:@"POST",@"Method",url,@"RequestURL",parms, @"Params",header,@"header",nil]);
#endif
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
//        if ([self isConnectionAvailable]) {
            [self POST:url parameters:parms constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
                NSData *data = UIImageJPEGRepresentation(image,1);
                NSString *fileName = [NSString stringWithFormat:@"%@.jpg", [self filenameFromDate:[NSDate date]]];
                [formData appendPartWithFileData:data name:(name == nil || name.length <=0)?@"image":name fileName:fileName mimeType:@"image/jpeg"];
            } success:^(AFHTTPRequestOperation *operation, id responseObject) {
                [self handleResult:subscriber responseObject:responseObject operation:operation url:url];
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                [subscriber sendError:error];
                [subscriber sendCompleted];
                NSLog(@"----请求结束----");
                NSLog(@"%@", [NSDictionary dictionaryWithObjectsAndKeys:url, @"RequestURL",error, @"ResultData", nil]);
            }];
//        } else {
//            [subscriber sendError:[NSError errorWithDomain:kNetworkUnavailableText code:kNetworkUnavailableCode userInfo:nil]];
//            [subscriber sendCompleted];
//#ifdef isPrint
//            NSLog(@"！！！！！！！！！！！请求结束！！！！！！！！！！！");
//#endif
//        }
        return nil;
    }];
}


//HTTP GET请求
- (RACSignal *)get:(NSString *)url parms:(NSDictionary *)parms {
    if (mBlock) {
        mBlock(self.requestSerializer);
    }
#ifdef isPrint
    NSDictionary *header = self.requestSerializer.HTTPRequestHeaders;
    NSLog(@"----请求开始----\n%@",[NSDictionary dictionaryWithObjectsAndKeys:@"GET",@"Method",url,@"RequestURL",parms,@"Params",header,@"header",nil]);
#endif
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
//        if ([self isConnectionAvailable]) {
            [self GET:url parameters:parms success:^(AFHTTPRequestOperation *operation, id responseObject) {
                [self handleResult:subscriber responseObject:responseObject operation:operation url:url];
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                [subscriber sendError:error];
                [subscriber sendCompleted];
#ifdef isPrint
                NSLog(@"----请求结束----");
                NSLog(@"%@", [NSDictionary dictionaryWithObjectsAndKeys:url, @"RequestURL",error, @"ResultData", nil]);
#endif
            }];
//        } else {
//            [subscriber sendError:[NSError errorWithDomain:kNetworkUnavailableText code:kNetworkUnavailableCode userInfo:nil]];
//            [subscriber sendCompleted];
//#ifdef isPrint
//            NSLog(@"！！！！！！！！！！！请求结束！！！！！！！！！！！");
//#endif
//        }
        return nil;
    }];
}

//HTTP POST请求
- (RACSignal *)post:(NSString *)url parms:(NSDictionary *)parms {
    if (mBlock) {
        mBlock(self.requestSerializer);
    }
#ifdef isPrint
    NSDictionary *header = self.requestSerializer.HTTPRequestHeaders;
    NSLog(@"----请求开始----\n%@",[NSDictionary dictionaryWithObjectsAndKeys:@"POST",@"Method",url,@"RequestURL",parms,@"Params",header,@"header",nil]);
#endif
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
//        if ([self isConnectionAvailable]) {
            [self POST:url parameters:parms success:^(AFHTTPRequestOperation *operation, id responseObject) {
                [self handleResult:subscriber responseObject:responseObject operation:operation url:url];
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                [subscriber sendError:error];
                [subscriber sendCompleted];
#ifdef isPrint
                NSLog(@"----请求结束----");
                NSLog(@"%@", [NSDictionary dictionaryWithObjectsAndKeys:url, @"RequestURL",error, @"ResultData", nil]);
#endif
            }];
//        } else {
//            [subscriber sendError:[NSError errorWithDomain:kNetworkUnavailableText code:kNetworkUnavailableCode userInfo:nil]];
//            [subscriber sendCompleted];
//#ifdef isPrint
//            NSLog(@"！！！！！！！！！！！请求结束！！！！！！！！！！！");
//#endif
//        }
        return nil;
    }];
}

//处理网络返回数据
- (void)handleResult:(id<RACSubscriber>)subscriber responseObject:(id)responseObject operation:(AFHTTPRequestOperation *)operation url:(NSString *)url{
    [self prepareHander:responseObject];
    [subscriber sendNext:responseObject];
    [subscriber sendCompleted];
#ifdef isPrint
    NSLog(@"----请求结束----");
    NSLog(@"%@", [NSDictionary dictionaryWithObjectsAndKeys:url, @"RequestURL",responseObject, @"ResultData", nil]);
#endif
}

- (void) prepareHander:(id) object {
    
}

@end
